package org.deltaset.meta.internal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 *
 * @author dmakariev
 */
public class MetaUtils {

    public final static String DEFAULT = "default";

    public static MetaClassImpl emptyMetaClass() {
        final EmptyDetail detail = emptyDetail();
        final MetaClassBuilder metaClassBuilder = MetaClassBuilder.newBuilder();
        metaClassBuilder.isEmpty(true).detail(detail);
        return metaClassBuilder.build();
    }

    public static MetaActionImpl emptyMetaAction() {
        final String id = null;
        final MetaClassImpl parentMetaClass = null;
        final MetaClassImpl parameterMetaClass = null;
        final MetaClassImpl returnMetaClass = null;

        final boolean isEmpty = true;
        final EmptyDetail detail = emptyDetail();
        return new MetaActionImpl(id, parentMetaClass, parameterMetaClass, returnMetaClass, isEmpty, detail);
    }

    public static MetaFieldImpl emptyMetaField() {
        final String id = null;
        final MetaClassImpl parentMetaClass = null;
        final MetaClassImpl propertyMetaClass = null;
        final String propertyName = null;
        final int max = -1;
        final int min = -1;
        final boolean isEmpty = true;

        return new MetaFieldImpl(id, parentMetaClass, propertyMetaClass, propertyName, max, min, isEmpty);
    }

    public static EmptyDetail emptyDetail() {
        return new EmptyDetail();
    }

    static <P> List<P> orderedFor(Map<String, P> valueMap, Map<String, List<String>> orderMap, String viewName) {
        final List<String> fieldIds = viewNameOrDefault(orderMap, viewName);

        final List<P> orderedFields = new ArrayList<P>(fieldIds.size());
        for (String fieldId : fieldIds) {
            final P metaField = valueMap.get(fieldId);
            orderedFields.add(metaField);
        }
        return orderedFields;
    }

    static List<String> viewNameOrDefault(Map<String, List<String>> idMap, String viewName) {
        if (idMap.containsKey(viewName)) {
            return defaultNull(idMap.get(viewName), Collections.EMPTY_LIST);
        } else {
            return defaultNull(idMap.get(DEFAULT), Collections.EMPTY_LIST);
        }

    }

    /**
     * Null-safe object defaulting.
     * Returns the object, or defaultValue if the object is null.
     */
    public static <T> T defaultNull(T object, T defaultValue) {
        if (null != object) {
            return object;
        }
        return defaultValue;
    }

    public static class EmptyDetail {
    }
}
